package org.apache.shiro.web.validator;

import javax.servlet.http.HttpServletRequest;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

import com.dhcc.DRGsHosp.infra.util.StringUtils;

/**
 * @title		:PortalLoginValidator.java
 * @description	:portal单点登录验证
 * @author		:WangTeng
 * @date		:2018年4月27日
 * @version     :1.0
 * @copyright   :DHCC 2013-2014 
 */
public class PortalLoginValidator extends LoginValidator{
	
	private String pticket;
	private String pcode;
	private String username;
	
	private String ticketValidateUrl;//portal 单点登录验证票据接口地址
	
	private String ticketValidateMethod;//portal 单点登录验证票据接口方法

	public PortalLoginValidator() {
		
	}
	/**
	 * @desc Portal系统单点登录验证
	 * @param httpRequest
	 * @param ticketValidateUrl
	 * @param ticketValidateMethod
	 */
	public PortalLoginValidator(HttpServletRequest httpRequest, String ticketValidateUrl, String ticketValidateMethod) {
		//Portal单点登录验证
		this.pticket = httpRequest.getParameter("ptickets");
		this.pcode = httpRequest.getParameter("pcode");
		this.ticketValidateUrl = ticketValidateUrl;
		this.ticketValidateMethod = ticketValidateMethod;
	}
	
	@Override
	public boolean hasRequiredParam(HttpServletRequest httpRequest) {
		this.pticket = httpRequest.getParameter("ptickets");
		this.pcode = httpRequest.getParameter("pcode");
		if (this.pticket != null && this.pcode != null) {
			return true;
		}
		return false;
	}

	@Override
	public boolean isValidate() {
		if (StringUtils.isEmpty(pticket) || StringUtils.isEmpty(pcode)) {
			return false;
		} else {
			JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
			Client client = factory.createClient(ticketValidateUrl);
			try {
				Object[] objects = client.invoke(ticketValidateMethod, pticket, pcode);
				System.out.println("portal return: "+objects[0]);
				
				if (!"-1".equals(objects[0])) {
					username= (String) objects[0];
					System.out.println("Portal登录");
					return true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
		
	}

	/* (non-Javadoc)
	 * @see org.apache.shiro.web.filter.LoginValidator#getUsername()
	 */
	@Override
	public String getUsername() {
		return username;
	}

	/**
	 * @return the ticketValidateUrl
	 */
	public String getTicketValidateUrl() {
		return ticketValidateUrl;
	}

	/**
	 * @param ticketValidateUrl the ticketValidateUrl to set
	 */
	public void setTicketValidateUrl(String ticketValidateUrl) {
		this.ticketValidateUrl = ticketValidateUrl;
	}

	/**
	 * @return the ticketValidateMethod
	 */
	public String getTicketValidateMethod() {
		return ticketValidateMethod;
	}

	/**
	 * @param ticketValidateMethod the ticketValidateMethod to set
	 */
	public void setTicketValidateMethod(String ticketValidateMethod) {
		this.ticketValidateMethod = ticketValidateMethod;
	}
	
	
}
